package com.binarycube.webserver.session;

import java.util.HashMap;
import java.util.Map;

import com.binarycube.webserver.config.SessionManagerConfig;
import com.binarycube.webserver.wrappers.WrappedRequest;
import com.binarycube.webserver.wrappers.WrappedResponse;

/**
 * Default Session manager uses cookies to track user sessions, and creates sessions 
 * @author chris
 *
 */
public class CookieSessionManager implements ISessionManager{
	Map<String, Session> sessions;
	private String cookieName = "sessionid";
	
	
	public  CookieSessionManager() {
		sessions = new HashMap<String,Session>();
	}
	
		
	public Session getSession(WrappedRequest request) {
		String id = request.getCookieValue(cookieName);
		if (id != null) {
			if (sessions.containsKey(id)) return sessions.get(id); 
		}
		return null;
		
	}
	
	
	public Session createSession(WrappedRequest request) {
		Session session = new Session(request);
		sessions.put(session.getID(), session);
		return session;
	}

	
	public void updateSession(Session session) {
		sessions.put(session.getID(), session);
	}
	
	
	public Session getSession(String id) {
		return sessions.get(id);
	}

	public void persistSession(WrappedResponse response, Session session) {
		if (session != null) response.addCookie(cookieName, session.getID(), (String)session.getProperty(Session.DOMAIN), 1000);
		
	}

	
	public void configure(SessionManagerConfig config) {
		String tmp = config.getProperty("cookieName");
		if (tmp != null) cookieName = tmp;
	}


	@Override
	public void endSession(WrappedResponse response, Session session) {
		if (session != null) response.addCookie(cookieName, null, (String)session.getProperty(Session.DOMAIN), 0);
		session.deActivate();
		sessions.remove(session.getID());
		
	}
	
}

